package infiniteLoop
{
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.TimerEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.utils.Timer;
	
	import spark.components.Label;
	
	import utils.StringTool;
	
	
	public class InfiniteLoop
	{
		public static var printMsg:Label;
		private var _path:String;
		private var _path2:String;
		private var _cfgStream:FileStream;
		private var _urlLoader:URLLoader;
		private var _timer:Timer;
		
		public function InfiniteLoop()
		{
			_timer = new Timer(1000);
		}
		public function doLoad(path:String):void
		{
			//"C:\Users\Administrator\Desktop\ani原始\21000\bg_tiles\1.mp"
			
			_path = path;
			_path2 = path.replace(".as", "-222.as");
			
			loadData();
		}
		private function loadData():void
		{
			var request:URLRequest = new URLRequest(_path);
			_urlLoader = new URLLoader();
			_urlLoader.addEventListener(Event.COMPLETE, onComplete1);
			_urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onLoadError1);
			_urlLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onLoadError2);
			_urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onLoadError3);
			_urlLoader.data = null;
			_urlLoader.dataFormat = URLLoaderDataFormat.TEXT;
			_urlLoader.load(request);
			
		}
		/**
		 * 可以针对所有代码。
		 */
		private function onComplete1(e:Event):void
		{
			_urlLoader.removeEventListener(Event.COMPLETE, onComplete1);
			_urlLoader.removeEventListener(IOErrorEvent.IO_ERROR, onLoadError1);
			_urlLoader.removeEventListener(HTTPStatusEvent.HTTP_STATUS, onLoadError2);
			_urlLoader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onLoadError3);
			
			var content:String = (_urlLoader.data);
			if(!content){
				return;
			}
			_urlLoader.close();
			
			var newStr:String = content;
				
			newStr = getInfiniteLoopStr(newStr, "for(");
			newStr = getInfiniteLoopStr(newStr, "for (");
			newStr = getInfiniteLoopStr(newStr, "while(");
			newStr = getInfiniteLoopStr(newStr, "while (");
			newStr = getInfiniteLoopStr(newStr, " function ");
				
			
			if(newStr == content){
				//不需要操作
				return;
			}
			
			var rootFile:File = new File();
			var fl:File = rootFile.resolvePath(_path2);
			
			try
			{
				_cfgStream = new FileStream();
				_cfgStream.open(fl, FileMode.WRITE);
				_cfgStream.writeUTFBytes(newStr);
				_cfgStream.close();
				
				_timer.addEventListener(TimerEvent.TIMER, onTimer2);
				_timer.start();
			}
			catch(e:Error)
			{
				throw new Error(e.getStackTrace());
			}
		}
		
		private static var _loopId:int = 0;
		/**
		 * 给每个函数、循环，加上 死循环函数检测。for(,while(, function ,
		 */
		private function getInfiniteLoopStr(newStr:String, checkStr:String = "for("):String
		{
			var index1:int = newStr.indexOf(checkStr);
			while(index1 != -1){
				if(checkStr == " function "){//已经注入了，不再重复
					if(newStr.indexOf(" function detectInfiniteLoop", index1 - 1) == index1){
						index1 = newStr.indexOf(checkStr, index1 + 30);
						continue;
					}
				}
				
				var functionIndex:int = newStr.indexOf("{", index1);
//				if(checkStr == " function "){//构造函数，不注入
//					var khIndex:int = newStr.lastIndexOf(")", functionIndex);
//					var khStr:String = newStr.substring(khIndex+1, functionIndex);
//					khStr = StringTool.trim(khStr);
//					if(!khStr){
//						index1 = newStr.indexOf(checkStr, index1 + 30);
//						continue;
//					}
//				}
				
				var loopIndex:int = newStr.indexOf("{Config.detectInfiniteLoop();", index1);
				if(functionIndex != loopIndex){
					var str1:String = newStr.substring(0, functionIndex+1);
					var str2:String = newStr.substring(functionIndex+1);
					var lineStr:String = "Config.detectInfiniteLoop("+_loopId+");";
					
					_loopId ++;
					
					newStr = str1 + lineStr + str2;
					
					index1 = newStr.indexOf(checkStr, index1 + lineStr.length);
				}
				else{
					index1 = newStr.indexOf(checkStr, index1 + 10);
				}
			}
			
			return newStr;
		}
		
		private function onTimer2(e:TimerEvent):void
		{
			var rootFile:File = new File();
			var fnew:File = rootFile.resolvePath(_path2);
			if(fnew.exists){
				
				_timer.removeEventListener(TimerEvent.TIMER, onTimer2);
				_timer.stop();
				_timer = null;
				
				var rootFile:File = new File();
				var fold:File = rootFile.resolvePath(_path);
				
				fnew.moveTo(fold, true);
			}
		}
		
		private function onLoadError1(e:Event):void
		{
			trace("加载是失败");
		}
		private function onLoadError2(e:HTTPStatusEvent):void
		{
			if(e.status >= 400){
				trace("加载是失败2,url="+e.target.url);
			}
		}
		private function onLoadError3(e:Event):void
		{
			trace("安全沙箱错误");
		}
		
		public static var dicIdCount:int = 0;
	}
}